#include "tablemodel.h"

TableModel::TableModel(
    QObject *parent)
    : QAbstractTableModel{parent}
{

}

int TableModel::rowCount(const QModelIndex &parent) const
{
    return m_items.size();
}

int TableModel::columnCount(const QModelIndex &parent) const
{
    return m_headerNames.size();
}

QVariant TableModel::data(const QModelIndex &index, int role) const
{
    if(!index.isValid() || index.row() >= rowCount())
        return QVariant();
    const TableItem *const item = items().at(index.row());
    if(role == Qt::DisplayRole) {
        return item->valueString(index.column());
    }
    else if(role == Qt::EditRole) {
        return item->value(index.column());
    }

    return QVariant();
}

bool TableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if(!index.isValid() || index.row() >= rowCount())
        return false;
    TableItem *item = items().at(index.row());
    if(role == Qt::EditRole) {
        bool ret = item->setValue(index.column(), value);
        if(ret)
            emit dataChanged(index, index);
        return ret;
    }
    return true;
}

Qt::ItemFlags TableModel::flags(const QModelIndex &index) const
{
    if(index.column() < itemFlags().size())
        return itemFlags().at(index.column());
    return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
}

QVariant TableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if(section < columnCount() && orientation == Qt::Horizontal && role == Qt::DisplayRole)
        return m_headerNames[section];
    return QVariant();
}

QStringList TableModel::headerNames() const
{
    return m_headerNames;
}

void TableModel::setHeaderNames(const QStringList &headerNames)
{
    m_headerNames = headerNames;
}

QList<TableItem *> TableModel::items() const
{
    return m_items;
}

void TableModel::setItems(const QList<TableItem *> &items)
{
    beginResetModel();
    if(m_items.size() > 0) {
        foreach (TableItem *item, m_items) {
            delete item;
        }
        m_items.clear();
    }
    m_items = items;
    endResetModel();
}

QList<Qt::ItemFlags> TableModel::itemFlags() const
{
    return m_itemFlags;
}

void TableModel::setItemFlags(const QList<Qt::ItemFlags> &itemFlags)
{
    m_itemFlags = itemFlags;
}

QList<ColumnType> TableModel::itemColumnTypes() const
{
    return m_itemColumnTypes;
}

void TableModel::setItemColumnTypes(const QList<ColumnType> &itemColumnTypes)
{
    m_itemColumnTypes = itemColumnTypes;
}

void TableModel::clearItems()
{
    beginResetModel();
    foreach (TableItem *item, m_items) {
        delete item;
    }
    m_items.clear();
    endResetModel();
}

void TableModel::addItem(TableItem *item)
{
    beginInsertRows(QModelIndex(), rowCount(), rowCount());
    insertRows(rowCount(), 1);
    m_items.append(item);
    endInsertRows();
}


